/**
 * 加解密的工具类
 * 使用：https://github.com/JuneAndGreen/sm-crypto
 *
 * @author yubaoshan
 */
import smCrypto from 'sm-crypto'

const sm2 = smCrypto.sm2
const cipherMode = 1 // 1 - C1C3C2，0 - C1C2C3，默认为1
const publicKey =
	'049979cf7f8cc6b9acc8f71ca6302d0f80376f1299ed573dde813cc770511daf9c770a88aa3d317d0314b4df1f12c3ff821b86b232caba57e8de3199c0fad6fae7'

class LocalEncrypt {
	constructor(crypto = smCrypto.sm2, kstr = '123221312112adfas3a39fs', cipherMode = 1) {
		this.crypto = crypto
		this._getKey(kstr)

		this.cipherMode = cipherMode
	}
	_getKey(kstr) {
		// debugger
		let keypair = this.crypto.generateKeyPairHex(kstr)
		this.publicKey = keypair.publicKey
		this.privateKey = keypair.privateKey
	}
	encode(str) {
		// console.log(1121, this.crypto,this.publicKey, this.cipherMode)
		// debugger
		const strStart = String(+new Date()).slice(-5)
		const strEnd = String(Math.random()).slice(-6)
		const _str = strStart + str + strEnd
		return this.crypto.doEncrypt(_str, this.publicKey, this.cipherMode)
	}
	decode(str) {
		// debugger
		return this.crypto.doDecrypt(str, this.privateKey, this.cipherMode).slice(5, -6)
	}
}
/**
 * 国密加解密工具类
 */
export default {
	// SM2加密
	doSm2Encrypt(msgString) {
		return sm2.doEncrypt(msgString, publicKey, cipherMode)
	},
	// SM2数组加密
	doSm2ArrayEncrypt(msgString) {
		return sm2.doEncrypt(msgString, publicKey, cipherMode)
	},
	localEncrypt: new LocalEncrypt()
}
